/**
 * 
 */
package com.google.code.jkippt.parser;

import java.io.IOException;
import java.util.Calendar;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

/**
 * GSon adapter for type Calendar.
 * @author Federico De Faveri defaveri@gmail.com
 */
public class CalendarAdapter extends TypeAdapter<Calendar> {

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void write(JsonWriter out, Calendar value) throws IOException {
		if (value!=null) out.value(value.getTimeInMillis());
		else out.nullValue();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Calendar read(JsonReader in) throws IOException {
		if (in.peek() == JsonToken.NULL) {
			in.nextNull();
			return null;
		}
		long time = in.nextLong();
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(time);
		return calendar;
	}

}
